package com.landis.temple.mobile;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * Main activity for Twitter Story App
 * 
 * @author John Landis 
 * @author Anton Kronaj
 *
 */

public class TwitterLibrary extends ListActivity implements OnClickListener
{
    public final static int CREATE_STORY   = 0;
    public final static int CREATE_CHAPTER = 1;
    
    // Context menu options for delete and cancel
    private static final int DELETE_ID = Menu.FIRST + 1;
    private static final int CANCEL_ID = Menu.FIRST + 2;
    
    private static TwitterStoryDatabase tsdb;
    private Cursor dbResults;
    private SimpleCursorAdapter adapter;
    
    // will be displayed on the app when someone logs in
    public static String userName = null;
    private TextView userView;
    
    // Filled with twitter user-name on credentials check
    private static long myId = -1;
    
    private static final String TAG = "TwitterLibrary";
    private  View add_button;
    
    /**
     * called when activity first started. also the activity in which the app opens up to.
     * check if the user of the app is logged in to twitter.
     * set appropriate prompt
     * open database
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        Log.d(TAG , "in onCreate()" );
        
        TwitterBackend.init(this);
        
        add_button = findViewById( R.id.create_button );
        
        add_button.setOnClickListener( this );
        if(!TwitterBackend.isLoggedIn)
        {
        	add_button.setVisibility(View.GONE);
        }
        else
        {
        	add_button.setVisibility(View.VISIBLE);
        }
        
        tsdb = new TwitterStoryDatabase( this.getApplication().getBaseContext() );
        tsdb = tsdb.open();       
              
        updateList();
        
        registerForContextMenu(getListView());
        
        TwitterBackend.testLogin(this);
        
        userView = (TextView) findViewById( R.id.username );
        if(userName != null) userView.setText( userName );
    }
    
    /**
     * called when a new intent is passed to this activity.
     * used after the user returns from webview to get the credentials from twitter.
     * resets the login prompt  
     * 
     * @see android.app.Activity#onNewIntent(android.content.Intent)
     */
    @Override
    protected void onNewIntent(Intent intent) 
    {
        Log.d( TAG , "in onNewIntent()" );
        super.onNewIntent(intent);
        TwitterBackend.process(intent, this);
        Log.d( TAG , "back in onNewIntent() from process()" );
        userName = TwitterBackend.getUsername();
        
        Toast.makeText(this,userName, Toast.LENGTH_LONG).show();
        userView.setText(userName);
        
        if(!TwitterBackend.isLoggedIn)
        {
        	add_button.setVisibility(View.GONE);
        }
        else
        {
        	add_button.setVisibility(View.VISIBLE);
        	setAuthor( userName );
        }	
    }
    
    /**
     * creates the option menu options that are bound to the devices menu button
     * 
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        return MyAppMenus.createMenu(menu, this, R.menu.library_menu);
    }

    
    /**
     * callback for the menu options
     * 
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        return MyAppMenus.menuItemSelected(item, this, myId);
    }
    
    /**
     * creates the context menu.
     * the menu that gets created when a list item is held for an extended period of time
     * 
     * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
     */
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle(R.string.app_name);
        menu.add(0, DELETE_ID, 0, R.string.menu_delete );
        menu.add(0, CANCEL_ID, 0, R.string.menu_cancel );
    }
    
    /**
     * callback for the context menu items
     * delete is the only option
     * 
     * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) 
    {
        switch(item.getItemId()) 
        {
            case DELETE_ID:
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                long author_id = tsdb.getStoryAuthor( info.id );
                
                if( author_id == myId )
                {    
                    String story = tsdb.getStoryTitle( info.id );
                    MySQLAccess.removeChapters( story );
                    MySQLAccess.removeStory( story );
                }
                
                tsdb.deleteStory(info.id);
                tsdb.deleteAllChapters(info.id);
                
                updateList();
                return true;
        }
        return super.onContextItemSelected(item);
    }
    
    /**
     * callback for list item clicked.
     * starts twitterstory activity to view chapters that are part of the story clicked
     * 
     * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
     */
    @Override
    protected void onListItemClick( ListView list , View view , int position, long id) 
    {
        super.onListItemClick( list , view , position , id );   
        
        Log.d( "OnListItemClicked" , "id is " + id );
        
        Intent intent = new Intent( this , TwitterStory.class );
        intent.putExtra( "story_id"  , id    );
        intent.putExtra( "author_id" , myId  );

        startActivity( intent );
    }
    
    /**
     * updates the the list that is displayed in the listview with the items stored in the local database
     */
    private void updateList() 
    {
        if( dbResults != null ) dbResults.close();

        
        dbResults = tsdb.getAllStories();
        
        startManagingCursor(dbResults);
      
        if( dbResults != null )
        {
            // xml defined views
            int to[] = new int[] {  R.id.story_id           , 
                                    R.id.story_author       , 
                                    R.id.story_title        , 
                                    R.id.story_date_created };
            
            // columns 
            String[] from = dbResults.getColumnNames();
            
            adapter = new SimpleCursorAdapter( this           , 
                                               R.layout.books , 
                                               dbResults      , 
                                               from           , 
                                               to             );
            setListAdapter(adapter);
        }
    }

    /**
     * action to be performed when the create story button is clicked. 
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View add_button) 
    {        
        Intent i = new Intent( this , CreateActivity.class );
        i.putExtra( "action"    , CREATE_STORY  );
        i.putExtra( "author_id" , myId          );
        
        startActivity( i );
    }   
    
    /**
     * if the authors twitter username does not exist in the database assign the username a unique long id.
     * Store the id and the username in the database if not already stored.
     * each story has a author.  the author of the story is the prson who started the story. 
     * @param author author twitter user name of the person who started this story.
     */
    public static void setAuthor( String author )
    {
        myId = tsdb.getAuthorId( author );
        Log.d( TAG , "new test " + tsdb.getAuthor(myId));

        if( myId < 0 )
        {
            Log.d( TAG , "user " + author + " created" );
            
            myId = tsdb.createAuthor( author );
            MySQLAccess.addAuthor( author );
        }
    }    
    
    /**
     * close database when activity is done.
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() 
    {
        Log.d( TAG , "in onDestroy" );
        
        super.onDestroy();        
        if( tsdb != null ) {
            tsdb.close();
        }
    }
    /**
     * not used.
     * @see android.app.Activity#onPause()
     */

    @Override
    protected void onPause() 
    {
        Log.d( TAG , "in onPause" );
        super.onPause();
    }


    /**
     * not used.
     * @see android.app.Activity#onRestart()
     */
    @Override
    protected void onRestart() 
    {
        Log.d( TAG , "in onRestart" );
        super.onRestart();
    }

    
    /**
     * not used
     * @see android.app.Activity#onStart()
     */
    @Override
    protected void onStart() 
    {
        Log.d( TAG , "in onStart" );
        super.onStart();
    }

    
    /**
     * not used.
     * @see android.app.Activity#onStop()
     */
    @Override
    protected void onStop() 
    {
        Log.d( TAG , "in onStop" );
        super.onStop();
    }
}
